package com.ah.http.resttemplate;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Tao on 2020/8/6
 */
public class RestTemplateUtil {

    /**
     *  将请求参数与请求头转换为 HttpEntity
     * @param paramsMap 请求参数
     * @param headersMap 请求头
     * @return
     */
    public static HttpEntity params_header_convert_httpEntity(Map<String, Object> paramsMap, Map<String, String> headersMap) {

        //初始化 传值参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();

        if (!paramsMap.isEmpty()){
            //转换body参数
            paramsMap.entrySet().stream().forEach(p -> {
                params.add(p.getKey(), JSON.toJSONString(p.getValue()).replace("\"", ""));
            });
        }

        if (!headersMap.isEmpty()){
            //转换请求头
            headersMap.entrySet().stream().forEach(h -> {
                headers.add(h.getKey(), h.getValue());
            });
        }

        //格式化参数
        HttpEntity<MultiValueMap<String, String>> HttpEntity = new HttpEntity<>(params, headers);

        return HttpEntity;
    }

    /**
     * get url+params
     * @param url 地址
     * @param paramMap 参数
     * @return
     */
    public static String url_with_params(String url,Map<String, Object> paramMap) {
        if (paramMap.isEmpty()){
            return url;
        }
        String urlParam = url + "?" + convert_sort_url_params(paramMap);
        return urlParam;
    }

    /**
     * 按key进行正序排列，之间以&相连
     * <功能描述>
     * @param params
     * @return
     */
    public static String convert_sort_url_params(Map<String, Object> params) {
        Map<String, Object> map = new TreeMap<>(Comparator.naturalOrder());
        map.putAll(params);

        StringBuffer stringBuffer = new StringBuffer();
        map.forEach((k,v)-> stringBuffer.append(k).append("=").append(v).append("&"));

        String str = stringBuffer.toString();

        if(str.length() > 0){
            str = str.substring(0, str.length()-1);
        }
        return str;
    }


    public static void main(String[] args) {
        String url = "https://192.168.30.222/api/login";
        Map<String, Object> headerMap1 = new HashMap<>();

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
        headerMap.put("Cookie", "JSESSIONID=74F526DEFBFD3A8E7C02D64AAAD66DE1");
        headerMap.put("Referer", "https://192.168.30.222/index.html");

        System.out.println(url_with_params(url, headerMap));
        System.out.println(url_with_params(url, headerMap1));


    }
}
